import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:changxindianzishangwu/dao/friends_circle_dao.dart';
import 'package:changxindianzishangwu/dao/user_info_dao.dart';
import 'package:changxindianzishangwu/model/address_book_model.dart';
import 'package:changxindianzishangwu/model/friends_lately_model.dart';
import 'package:changxindianzishangwu/model/user_info_model.dart';
import 'package:changxindianzishangwu/pages/contacts/set_friend_nickname_page.dart';
import 'package:changxindianzishangwu/pages/find/find_page.dart';
import 'package:changxindianzishangwu/pages/home_page.dart';
import 'package:changxindianzishangwu/pages/message/chat/message_c2c_page.dart';
import 'package:changxindianzishangwu/provider/nickname.dart';
import 'package:changxindianzishangwu/util/app_color.dart';
import 'package:changxindianzishangwu/util/app_string.dart';
import 'package:changxindianzishangwu/util/colors.dart';
import 'package:changxindianzishangwu/util/fade_router.dart';
import 'package:changxindianzishangwu/util/head_url.dart';
import 'package:changxindianzishangwu/util/universal_view.dart';
import 'package:changxindianzishangwu/widget/gallery_watcher.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_conversation.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_info_result.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_user_full_info.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_value_callback.dart';
import 'package:tencent_im_sdk_plugin/tencent_im_sdk_plugin.dart';

import 'friend_settings.dart';

class ConversationFriendPage extends StatefulWidget {
  AddressBookModel model;
  int type;

  ConversationFriendPage({Key key, this.model, this.type = 1})
      : super(key: key);

  @override
  _ConversationFriendPageState createState() => _ConversationFriendPageState();
}

class _ConversationFriendPageState extends State<ConversationFriendPage> {
  // ConversationResultEntity _data;
  //
  // _onRefresh() {
  //   TencentImPlugin.sendMessage(
  //       node: TextMessageNode(content: "发起对话"),
  //       receiver: widget.userEntity.userID);
  //   Get.to(MessageC2cPage());
  // }
  //
  List<V2TimFriendInfoResult> friendInfoResult;
  V2TimUserFullInfo userEntity;
  String name = "";

  getData() async {
    V2TimValueCallback<List<V2TimFriendInfoResult>> user =
    await TencentImSDKPlugin.v2TIMManager.v2TIMFriendshipManager
        .getFriendsInfo(userIDList: [widget.model.userId]);

    if (user.code == 0) {
      friendInfoResult = user.data;
      if (friendInfoResult != null && friendInfoResult.length > 0) {
        friendInfoResult.forEach((element) {
          userEntity = element.friendInfo.userProfile;
        });
      }
    }
    Provider.of<NickName>(context, listen: false).add(widget.model.name);
    setState(() {});
  }

  getLateLy() async {
    return await FriendsCircleDao.getFriendsLately(widget.model.userId);
  }

  UserInfoModel userInfoModel;
  var ziYuId = "";

  getServiceData() async {
    userInfoModel =
    await UserInfoDao.getUserInfo(userId: int.parse(widget.model.userId));
    setState(() {
      ziYuId = userInfoModel.data.account;
    });
  }

  _getConversation() async {
    Get.to(
            () => MessageC2cPage(widget.model.name, 1, widget.model.userId,
            widget.model.headerUrl, "c2c_" + widget.model.userId),
        arguments: V2TimConversation(
            userID: widget.model.userId,
            showName: widget.model.name,
            faceUrl: widget.model.headerUrl,
            conversationID: "c2c_" + widget.model.userId));
    // V2TimValueCallback<V2TimMessage> res = await TencentImSDKPlugin.v2TIMManager
    //     .getMessageManager()
    //     .sendTextMessage(
    //       text: "wwww",
    //       receiver: "${widget.model.userId}",
    //     );
    // if (res != null) {
    //   print(res.data.toJson());
    // }
  }

  //
  // _onConversationClick(ConversationEntity data) {
  //   Get.to(() => MessageC2cPage(), arguments: data);
  // }
  @override
  Widget build(BuildContext context) {
    name = Provider.of<NickName>(context).name;
    print("this:::" + name);

    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          onPressed: () {
            if (widget.type == 2) {
              Navigator.pushAndRemoveUntil(
                  context,
                  FadeRoute(HomePage(
                    pageIndex: 1,
                  )),
                      (route) => false);
            } else if (widget.type == 4) {
              Get.back();
            }
          },
          icon: Icon(Icons.arrow_back_ios),
        ),
        elevation: 0,
        actions: [
          IconButton(
            icon: Image.asset(
              "images/message/更多.png",
              fit: BoxFit.cover,
              height: width(22),
              width: width(22),
            ),
            onPressed: () {
              Get.to(() => FriendSettings(
                userId: widget.model.userId,
              ));
            },
          ),
          Container(width: 8),
        ],
      ),
      body: GestureDetector(
        onHorizontalDragUpdate: (details) {
          print("============${details.globalPosition.dx}");
          if (details.globalPosition.dx > 100) {
            if (widget.type == 2) {
              Navigator.pushAndRemoveUntil(
                  context,
                  FadeRoute(HomePage(
                    pageIndex: 1,
                  )),
                      (route) => false);
            }
          }
        },
        child: Container(
          height: double.infinity,
          child: ListView(
            shrinkWrap: true,
            children: <Widget>[
              _headTop(context),

              _buildRemarks(),
              _buildDynamic(),
              UniversalView().line(),

              _buildText(),
              UniversalView().line(),
              //todo 个人信息更多隐藏
              // Container(
              //   color: Colors.white,
              //   height: ScreenUtil().setHeight(55),
              //   child: ListTile(
              //     leading: Text(
              //       "更多",
              //       style: TextStyle(
              //         fontSize: ScreenUtil().setSp(15),
              //       ),
              //     ),
              //     trailing: Icon(Icons.keyboard_arrow_right),
              //   ),
              // ),
              SizedBox(
                height: height(10),
              ),
              TextButton.icon(
                onPressed: _getConversation,
                icon: Image.asset(
                  "images/ic_message_green.png",
                  width: width(15),
                  height: width(15),
                ),
                label: Text(
                  "发送消息",
                  style: TextStyle(
                      fontSize: ScreenUtil().setSp(15),
                      color: Color.fromRGBO(0, 220, 169, 1)),
                ),
                style: ButtonStyle(
                    padding:
                    MaterialStateProperty.all(EdgeInsets.all(width(15))),
                    backgroundColor: MaterialStateProperty.all(Colors.white)),
              ),
            ],
          ),
        ),
      ),
    );
  }

  _buildText() {
    return Container(
        color: Colors.white,
        padding: EdgeInsets.all(width(15)),
        child: Row(
          children: [
            Expanded(
              flex: 1,
              child: Text(
                "来源",
                style: TextStyle(
                  fontSize: ScreenUtil().setSp(15),
                ),
              ),
            ),
            Text(
              "用户ID搜索",
              style: TextStyle(
                  fontSize: ScreenUtil().setSp(15),
                  color: Color.fromRGBO(153, 153, 153, 1)),
            ),
          ],
        ));
  }

  InkWell _buildDynamic() {
    return InkWell(
      onTap: () {
        Get.to(() => FindPage(
          widget.model.userId,
          isOnlyUser: true,
        ));
      },
      child: Container(
          margin: EdgeInsets.only(top: 10),
          color: Colors.white,
          height: 60,
          padding: EdgeInsets.only(
              left: width(15),
              right: width(15),
              top: width(5),
              bottom: width(5)),
          child: Row(
            children: [
              Text(
                "动态",
                style: TextStyle(
                  fontSize: ScreenUtil().setSp(15),
                ),
              ),
              Expanded(
                flex: 1,
                child: Container(
                    margin: EdgeInsets.only(
                        left: ScreenUtil().setWidth(1)),
                    child: getLateLyBuilder()),
              ),
              Icon(
                Icons.keyboard_arrow_right,
                color: Colors.grey,
              )
            ],
          )),
    );
  }

  InkWell _buildRemarks() {
    return InkWell(
      onTap: () {
        Get.to(
              () => SetFriendNicknamePage(
              userId: widget.model.userId, name: name),
        );
      },
      child: Container(
          color: Colors.white,
          margin: EdgeInsets.only(top: 10),
          padding: EdgeInsets.all(width(15)),
          child: Row(
            children: [
              Expanded(
                flex: 1,
                child: Text(
                  "备注和标签",
                  style: TextStyle(
                    fontSize: ScreenUtil().setSp(15),
                  ),
                ),
              ),
              Icon(
                Icons.keyboard_arrow_right,
                color: Colors.grey,
              ),
            ],
          )),
    );
  }

  ///头像 昵称 用户ID 个性签名
  Container _headTop(BuildContext context) {
    String usersign = userEntity != null
        ? userEntity.selfSignature == null
        ? ""
        : userEntity.selfSignature
        : widget.model.self ?? "";
    return Container(
      color: Colors.white,
      padding: EdgeInsets.only(
          left: width(15), right: width(15), top: width(10), bottom: width(10)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            children: <Widget>[
              InkWell(
                onTap: () {
                  _openGalleryWatcher(context, widget.model.headerUrl);
                },
                child: HeadView(
                    widget.model.headerUrl ?? HEADER_URL, width(55), width(55)),
              ),
              SizedBox(
                width: width(15),
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    name ?? "",
                    style: TextStyle(
                      fontSize: ScreenUtil().setSp(20),
                      color: Color.fromRGBO(51, 51, 51, 1),
                    ),
                  ),
                  SizedBox(
                    height: height(1),
                  ),
                  Row(
                    children: [
                      Text(
                        "昵称：" + userEntity.nickName,
                        style: TextStyle(
                          fontSize: ScreenUtil().setSp(12),
                          color: Color.fromRGBO(153, 153, 153, 1),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(left: 6),
                        child: Image.asset(
                          userEntity.gender == 2
                              ? AppString.IMAGE_NV
                              : AppString.IMAGE_NAN,
                          height: height(12),
                        ),
                      ),
                    ],
                  ),
                  SizedBox(
                    height: height(1),
                  ),
                  Text(
                    "用户ID：" + ziYuId,
                    style: TextStyle(
                      fontSize: ScreenUtil().setSp(12),
                      color: Color.fromRGBO(153, 153, 153, 1),
                    ),
                  ),
                ],
              ),
            ],
          ),
          Container(
            margin: EdgeInsets.only(top: 6),
            child: UniversalView().line(indent: 70),
          ),
          // 签名
          Container(
            margin: EdgeInsets.only(
                left: width(70), right: width(15), top: height(10)),
            child: Text(
              usersign,
              textAlign: TextAlign.left,
              style: TextStyle(
                fontSize: ScreenUtil().setSp(12),
                color: Color.fromRGBO(51, 51, 51, 1),
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    getData();
    getServiceData();
  }

  ///获取好友详情动态略缩图展示
  getLateLyBuilder() {
    return FutureBuilder(
        future: getLateLy(),
        builder: (context, sp) {
          if (sp.connectionState == ConnectionState.done && sp.data != null) {
            List<LatelyBean> data = sp.data;
            print('-------返回数据：${json.encode(data)}');
            return ListView.builder(
                scrollDirection: Axis.horizontal,
                itemCount: data.length,
                itemBuilder: (context, int index) {
                  return Container(
                    margin: EdgeInsets.only(left: ScreenUtil().setWidth(8)),
                    child: HeadView(
                        data[index].type == 2
                            ? data[index].url
                            : BACKGROUND_IMAGE,
                        ScreenUtil().setWidth(50),
                        ScreenUtil().setWidth(50)),
                  );
                });
          } else {
            return SizedBox();
          }
        });
  }

  _openGalleryWatcher(BuildContext context, String path) {
    List<String> artImage = [];
    artImage.add(path);
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => GalleryPhotoViewWrapper(
          thumbGalleryItems: artImage,
          tagItems: artImage,
          backgroundDecoration: const BoxDecoration(
            color: Colors.black,
          ),
          initialIndex: 1,
          scrollDirection: Axis.horizontal,
        ),
      ),
    );
  }
}
